<script setup>
  import emptyAddress from '@/assets/image/empty_address.png'
  import AddAddress from "../center/address/component/AddAddress.vue"
  import {addressList} from '@/api/address'
  import {queryCartCoupon, exChangeCoupon, preShopInfo} from '@/api/shopping'
  import {createOrder} from '@/api/shopping'
  import useSettingStore from '@/store/modules/setting'
  import defaultGoodImg from '@/assets/image/default_good.png'
  import couponEmpty from '@/assets/image/coupon_empty.png'
  import {t} from '@/locales'
  import { showToast } from 'vant'
  import {formatDateTime} from '@/utils'

  const router = useRouter()
  const currency = ref(useSettingStore().global.currencySymbol || '')

  const props = defineProps({
    query: {
      type: Object,
      default: () => {}
    }
  })
  const emits = defineEmits(['reload'])
  // 订单确认数据
  const preOrder = ref({})
  const preLoading = ref(false)

  const productList = computed(() => {
    const {carts} = preOrder.value
    if(carts?.length) {
      carts.forEach(it => {
        it.image = it.image.split(',')[0]
      })
    }
    return carts || []
  })
  // 地址
  const address = ref([])
  const selectedAddressId = ref('')
  // 购物车可用优惠券
  const couponList = ref([])
  // 优惠券兑换码
  const couponCode = ref('')
  const couponExpand = ref(true)
  // 摘要
  const showOrderInfo = ref(false)
  // 收地地址
  const open = ref(false)
  // 积分
  const useIntegral = ref(false)
  // 订单摘要
  const countList = computed(() => {
    const info = preOrder.value
    return [
      { label: ft('orderSum'), value: `${ft('selected')}${info.totalNum || 0}${ft('goodNum')}` },
      { label: ft('tPrice'), value: info.totalPrice || 0, showUnit: false},
      { label: ft('salePro'), value: info.couponPrice || 0, showUnit: false },
      { label: ft('toOffset'), value: info.integralDeduct || 0, showUnit: false },
      { label: ft('poster'), value: info.totalPostage || 0, showUnit: false },
      { label: ft('tax'), value: info.taxation || 0 },
      { label: ft('realPrice'), value: info.payPrice || 0, showUnit: false }
    ]
  })
  const selectedAdressList = computed(() => {
    if(!selectedAddressId.value) return []
    return address.value.filter(it=>it.addressId===selectedAddressId.value)
  })

  // 新增地址
  const addressRef = ref()

  function clickNewAddress(item) {
    addressRef.value.show(item)
  }
  // 获取地址列表
  function getAddressList() {
    addressList({pageNum: 1, pageSize: 99}).then(r => {
      const {rows} = r
      rows.forEach(it => {
        if(it.isDefault===1) {
          it.checked = true
          selectedAddressId.value = it.addressId
        }
      })
      address.value = r.rows
    })
  }
  // 开启地址选择器
  function openAddressSelector() {
    address.value.forEach(it => {
      it.checked = it.addressId===selectedAddressId.value
    })
    open.value = true
  }
  // 勾选地址
  function refreshAddress(item) {
    const {checked, addressId} = item
    if(checked) {
      address.value.forEach(it => {
        if(it.addressId!==addressId) it.checked = false
      })
    }
  }
  // 确认勾选地址
  function confirmAddress() {
    const chooseItem = address.value.find(it=>it.checked)
    if(chooseItem) {
      selectedAddressId.value = chooseItem.addressId
      init(true)
      open.value = false
    } else {
      showToast(t('commodity.addressRequired'))
    }
  }
  // 选择优惠券
  function selectCoupon(item) {
    couponList.value.forEach(it => {
      if(it.detailId===item.detailId) {
        it.checked = !it.checked
      } else {
        it.checked = false
      }
    })
    init(true)
  }
  function ft(field) {
    return t(`commodity.${field}`)
  }
  // 获取已选择的地址和优惠券
  function getCouponAddress() {
    const selectedCoupon = couponList.value.find(it=>it.checked)
    const ob = {}
    // 地址
    if(selectedAddressId.value) ob.addressId = selectedAddressId.value
    // 优惠券
    if(selectedCoupon) {
      ob.couponId = selectedCoupon.detailId
    } else {
      ob.isDefaultCoupon = 0
    }
    // 积分
    if(useIntegral.value) {
      ob.payIntegral = preOrder.value.useIntegralOptions[0]
    }
    return ob
  }
  // 兑换优惠券
  function getCoupon() {
    if(!couponCode.value) return showToast(t('commodity.exchangeTip'))
    exChangeCoupon(couponCode.value).then(r => {
      queryCoupon()
    })
  }
  // 可用优惠券
  function queryCoupon() {
    const {cartIds} = props.query
    queryCartCoupon({cartIds}).then(r => {
      const {rows=[]} = r
      if(!r.total) couponExpand.value = false
      rows.forEach(it => {
        it.checked = it.detailId === preOrder.value.couponId
      })
      couponList.value = rows
    })
  }
  // 提交订单
  function submit() {
    const {cartIds} = props.query
    const {addressValid} = preOrder.value
    const {addressId} = getCouponAddress()
    if(!addressId) return showToast(t('commodity.addressRequired'))
    if(!addressValid) return showToast(t('commodity.unAdd'))
    createOrder({cartIds: cartIds.split(','), ...getCouponAddress()}).then(r => {
      router.push({path:'/shopping', query: {orderId: r.data}})
    })
  }
  // 初始化数据
  function init(isRefresh=false) {
    // 查询下单前的订单信息
    const ob = isRefresh?getCouponAddress():{}
    const { cartIds } = props.query
    const { couponId = '' } = ob
    const params = {
      cartIds: cartIds.split(','),
      type: 0,
      isDefaultCoupon: couponId ? 0 : 1
    }
    Object.assign(params, ob)
    preLoading.value = true
    preShopInfo(params).then(r => {
      const { data } = r
      data.couponPrice = data.discountAmount
      preOrder.value = r.data
      preLoading.value = false
      // 初始购物券和地址数据
      if(!isRefresh) {
        getAddressList()
        queryCoupon()
      }
    })
  }

  init()
</script>

<template>
  <div class="order">
    <div class="p16">
      <div class="address">
        <p class="title">{{$t('commodity.chooseAdd')}}</p>
        <div class="address-list" v-if="selectedAdressList.length">
          <div class="a-item-cell" v-for="item in selectedAdressList" :key="item.addressId">
            <div class="a-item">
              <p>
                <!-- <van-checkbox
                  class="s-checkbox"
                  shape="square"
                  checked-color="#262626"
                  v-model="item.checked"
                  @click="refreshAddress(item)"
                /> -->
                <span>{{item.firstName}} {{item.lastName}}</span>
              </p>
              <p>{{item.province}}{{item.city}}{{item.detail}}</p>
              <p>{{item.phone}}，{{$t('commodity.postCode')}}({{item.postCode}})</p>
              <p>{{item.country}}</p>
              <p>
                {{item.isDefault===1?$t('commodity.dAddress')+' |':''}}
                <span @click="openAddressSelector">{{ $t('commodity.switch') }}</span>
              </p>
            </div>
            <p class="tip-text" v-if="preOrder.addressValid===false&&item.checked&&!preLoading">*{{$t('commodity.unAdd')}}</p>
          </div>
          <van-button class="s-btn h32 w-auto line-btn" @click="clickNewAddress(false)">
            <template #icon>
              <i class="iconfont icon-jia1"/>
            </template>
            {{$t('commodity.addAddress')}}
          </van-button>
        </div>
        <div class="empty" v-else>
          <img alt="" :src="emptyAddress"/>
          <p>{{$t('commodity.noAdd')}}</p>
          <van-button class="s-btn h32 w-auto line-btn" @click="clickNewAddress(false)">
            <template #icon>
              <i class="iconfont icon-jia1"/>
            </template>
            {{$t('commodity.addAddress')}}
          </van-button>
        </div>
      </div>
      <div class="product-list">
        <p class="title">{{$t('commodity.orderList')}}</p>
        <div
          class="list-item flex-bt"
          v-for="(it ,i) in productList"
          :key="i"
        >
          <img :src="it.image || defaultGoodImg" alt=""/>
          <div class="pro-info flex-bt">
            <div class="sku-name">
              <p>{{it.productName}}</p>
              <p><span>{{$t('commodity.sku')}}：</span>{{it.sku}}</p>
            </div>
            <div class="price flex-bt">
              <p>{{currency}}{{it.price}}</p>
              <p>x{{it.num}}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="coupon">
        <p class="title" @click="couponExpand=!couponExpand">
          {{$t('commodity.ableCoupon')}}
          <span>({{couponList.length}})</span>
          <span :class="['icon', couponExpand?'expand':'']"/>
        </p>
        <div class="coupon-con" v-if="couponExpand">
          <div class="exchange-cell">
            <van-field
              class="search-input"
              :placeholder="$t('commodity.exchangeTip')"
              v-model.trim="couponCode"
            >
              <template #button>
                <span @click="getCoupon">{{$t('commodity.exchange')}}</span>
              </template>
            </van-field>
            <div class="coupon-list" v-if="couponList.length">
              <div
                @click="selectCoupon(item)"
                :class="['item', item.checked?'active':'']"
                v-for="(item, i) in couponList"
                :key="i">
                <div class="l-item">
                  {{item.couponType===1?`${currency}${item.couponValue}`:`${item.discount*10}%`}}
                </div>
                <div class="r-item">
                  <p>{{item.threshold?`${$t('commodity.conAmount')} ${currency}${item.threshold}`:$t('commodity.comCoupon')}}</p>
                  <p>{{formatDateTime(item.expirationTime)}}{{$t('commodity.expir')}}</p>
                </div>
                <div class="selected" v-if="item.checked"/>
              </div>
              <p class="tips" v-if="preOrder.couponPrice">
                {{$t('commodity.couponFir')}} 1 {{$t('commodity.couponSec')}}，{{$t('commodity.couponThir')}}{{currency}}{{preOrder.couponPrice}}
              </p>
            </div>
            <div class="empty-coupon" v-else>
              <img :src="couponEmpty"/>
              <p>{{$t('commodity.noCoupon')}}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="integral">
        <p class="title">
          {{ $t('commodity.ablePoint') }} （{{preOrder.integralBalance}}）
        </p>
        <div v-if="preOrder.useIntegralOptions?.length" class="c-text">
          <van-checkbox
            class="s-checkbox"
            shape="square"
            checked-color="#262626"
            v-model="useIntegral"
            @click="()=>{init(true)}"
          />
          <span>
            {{ $t('commodity.use') }}{{preOrder.useIntegralOptions[0]}}{{ $t('commodity.toOffset') }}{{preOrder.useIntegralOptions[1]}}
          </span>
        </div>
      </div>
    </div>
    <van-sticky position="bottom">
      <div class="submit-cell flex-bt">
        <div class="total-price">
          <p>{{$t('commodity.totalNum')}}: {{currency}}{{preOrder.payPrice }}</p>
          <p @click="showOrderInfo=true">
            {{$t('commodity.orderInfo')}}
            <i class="iconfont icon-xiangshang"/>
          </p>
        </div>
        <van-button class="s-btn w-auto" @click="submit">{{$t('commodity.subOrder')}}</van-button>
      </div>
    </van-sticky>
    <!-- 订单摘要 -->
    <van-popup
      v-model:show="showOrderInfo"
      position="bottom"
    >
      <div class="order-info">
        <p class="title">{{$t('commodity.orderInfo')}}</p>
        <div class="info-cell">
          <div
            class="info-item flex-bt"
            v-for="(it ,i) in countList"
            :key="i"
          >
            <p>{{it.label}}</p>
            <p><span v-if="it.showUnit">{{currency}}</span> {{it.value}}</p>
          </div>
        </div>
      </div>
      <div class="submit-cell flex-bt">
        <div class="total-price">
          <p>{{$t('commodity.totalNum')}}: {{currency}}{{preOrder.payPrice }}</p>
          <p @click="showOrderInfo=false">
            {{$t('commodity.orderInfo')}}
            <i class="iconfont icon-xiangxia"/>
          </p>
        </div>
        <van-button class="s-btn w-auto" @click="submit">{{$t('commodity.subOrder')}}</van-button>
      </div>
    </van-popup>
    <!-- 地址选择列表 -->
    <van-popup
      v-model:show="open"
      position="bottom"
      style="max-height: 70%"
    >
      <div class="address-list-modal">
        <div class="adress-con">
          <p class="m-title">{{ $t('commodity.switchAdd') }}</p>
          <ul>
            <li v-for="item in address" :key="item.addressId" :class="['address-item', item.checked?'active':'']">
              <div class="name">
                <van-checkbox
                  class="s-checkbox"
                  shape="square"
                  checked-color="#262626"
                  v-model="item.checked"
                  @click="refreshAddress(item)"
                />
                <span>{{item.firstName}} {{item.lastName}}</span>
              </div>
              <div class="info">
                <p>{{item.province}}{{item.city}}{{item.detail}}</p>
                <p>{{item.phone}}，{{$t('commodity.postCode')}}({{item.postCode}})</p>
                <p>{{item.country}}</p>
              </div>
              <div class="default-address" v-if="item.isDefault===1">{{ $t('commodity.dAddress') }}</div>
            </li>
          </ul>
        </div>
        <van-sticky position="bottom">
          <div class="btn-list">
            <van-button class="s-btn c-gray w-auto" @click="open=false">{{$t('common.cancel')}}</van-button>
            <van-button class="s-btn w-auto" @click="confirmAddress">{{$t('common.confirm')}}</van-button>
          </div>
        </van-sticky>
      </div>
    </van-popup>
    <AddAddress @rest="getAddressList" ref="addressRef"/>
  </div>
</template>

<style lang="scss" scoped>
  .order {
    .p16 {
      padding: 16px;
      box-sizing: border-box;
    }
    .title {
      font-size: 14px;
    }
    .address {
      margin-bottom: 32px;
      .s-btn {
        font-size: 12px;
      }
      .empty {
        text-align: center;
        padding-top: 16px;
        img {
          width: 100px;
          height: 100px;
        }
        p {
          font-size: 14px;
          color: #8C8C8C;
          margin: 4px 0 16px;
        }
      }
      .address-list {
        .a-item {
          border-radius: 2px 2px 2px 2px;
          border: 2px solid #262626;
          padding: 16px;
          margin-top: 8px;
          p {
            font-size: 12px;
            &:nth-child(1), &:nth-child(3) {
              margin-bottom: 16px;
              span {
                font-weight: 600;
              }
            }
            &:nth-child(2) {
              margin-bottom: 4px;
            }
            &:nth-child(5) {
              margin-top: 16px;
              color: #8C8C8C;
              span {
                color: #262626;
              }
            }
          }
        }
        .tip-text {
          font-size: 12px;
          color: #FD2A53;
          margin-top: 4px;
        }
      }
    }
    .product-list {
      border-bottom: 1px solid #E5E5E5;
      margin-bottom: 24px;
      .title {
        margin-bottom: 16px;
      }
      .list-item {
        column-gap: 12px;
        height: 100px;
        padding: 16px;
        border-top: 1px solid #E5E5E5;
        img {
          height: 100px;
          width: 98px;
        }
        .pro-info {
          width: calc(100% - 110px);
          flex-direction: column;
          .sku-name {
            p {
              &:nth-child(1) {
                font-size: 14px;
                font-weight: 600;
                margin-bottom: 8px;
              }
              &:nth-child(2) {
                font-size: 12px;
                span {
                  color: #666666;
                }
              }
            }
          }
          .price {
            p{
              &:nth-child(1) {
                font-weight: 600;
                font-size: 14px;
              }
              &:nth-child(2) {
                font-size: 12px;
                color: #8C8C8C;
              }
            }
          }
        }
      }
    }
    .coupon {
      margin-bottom: 24px;
      .title {
        margin-bottom: 12px;
        .icon {
          display: inline-block;
          border-style: solid;
          border-width:8px 8px 0 8px;
          border-color:#262626 transparent transparent transparent;
          margin-left: 6px;
          transition: all  .5 linear;
          &.expand {
            transform: rotate(180deg);
          }
        }
      }
      .coupon-con {
        :deep(.search-input){
          height: 44px;
          border: 1px solid #262626;
          border-radius: 2px;
          padding: 0 12px;
          margin-bottom: 12px;
          .van-field__left-icon {
            line-height: 44px;
          }
          .van-field__button  {
            span {
              font-size: 14px;
              padding-left: 12px;
              display: inline-block;
              border-left: 1px #E5E5E5 solid;
              color: #262626;
            }
          }
          .van-field__body {
            height: 44px;
          }
        }
        .empty-coupon {
          text-align: center;
          padding: 20px 0;
          img {
            width: 100px;
            height: 100px;
          }
          p {
            font-size: 14px;
            color: #8C8C8C;
            margin: 4px 0 16px;
          }
        }
        .coupon-list {
          .item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            height: 102px;
            border-width: 1px 1px 1px 4px;
            border-color: #666666;
            background: #FAFAFA;
            border-style: solid;
            box-sizing: border-box;
            position: relative;
            color: #666666;
            &::before {
              content: '';
              display: block;
              width: 14px;
              height: 7px;
              border: 1px #666666 solid;
              border-radius: 0 0 50% 50%/0 0 100% 100% ;
              border-top: none;
              background: #FFFFFF;
              left: 103px;
              top: -1px;
              position: absolute;
            }
            &::after {
              content: '';
              display: block;
              width: 14px;
              height: 7px;
              border: 1px #666666 solid;
              border-radius: 50% 50% 0 0/100% 100% 0 0;
              border-bottom: none;
              background: #FFFFFF;
              left: 103px;
              bottom: -1px;
              position: absolute;
            }
            .l-item {
              width: 110px;
              box-sizing: border-box;
              border-right: 1px #8C8C8C dashed;
              height: 100%;
              text-align: center;
              line-height: 102px;
              font-weight: 600;
              font-size: 24px;
            }
            .r-item {
              p {
                font-size: 12px;
                text-indent: 16px;
                &:nth-child(1) {
                  margin-bottom: 16px;
                  font-weight: 600;
                  font-size: 14px;
                }
                &:nth-child(2) {
                  color: #666666;
                }
              }
            }
            .selected {
              position: absolute;
              right: -4px;
              top: -13px;
              width: 0;
              height: 0;
              display: block;
              border-style: solid;
              border-width:20px 0px 20px 20px;
              border-color: transparent transparent transparent #262626;
              transform: rotate(-45deg);
              &::before {
                box-sizing: border-box;
                position: absolute;
                inset-inline-start: 21.5%;
                display: table;
                width: 5.7142857142857135px;
                height: 9.142857142857142px;
                border: 2px solid #FFFFFF;
                border-top: 0;
                border-inline-start: 0;
                content: '';
                opacity: 1;
                transform: rotate(90deg) scale(1) translate(-50%, -50%);
                transition: all 0.2s cubic-bezier(0.12, 0.4, 0.29, 1.46) 0.1s;
                top: -2px;
                left: -19px;
              }
            }
            &.active {
              color: #262626;
              border-color: #262626;
              &::before, &::after {
                border-color: #262626;
              }
            }
          }
          .tips {
            font-size: 12px;
            color: #8C8C8C;
            margin-top: 6px;
          }
        }
      }
    }
    .integral {
      .c-text {
        margin-top: 12px;
        font-size: 12px;
        color: #8C8C8C;
        .s-checkbox {
          margin-right: 8px;
        }
      }
    }
    .submit-cell {
      padding: 10px 16px;
      border-top: 1px solid #ECEBF0;
      align-items: center;
      background: #ffffff;
      .total-price {
        p {
          &:nth-child(1) {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 2px;
          }
          &:nth-child(2) {
            font-size: 12px;
            color: #666666;
            .iconfont {
              vertical-align: middle;
            }
          }
        }
      }
    }
    :deep(.van-popup) {
      .order-info {
        padding: 16px;
        .title {
          margin-bottom: 24px;
        }
        .info-cell {
          .info-item {
            p {
              font-size: 14px;
            }
            &:nth-child(n + 2) {
              margin-bottom: 8px;
            }
            &:first-child,
            &:nth-child(6) {
              padding-bottom: 24px;
              margin-bottom: 24px;
              border-bottom: 1px #e5e5e5 solid;
            }
            &:last-child {
              margin-bottom: 24px;
            }
          }
        }
      }
      .address-list-modal {
        height: 100%;
        box-sizing: border-box;
        .adress-con {
          padding: 16px 16px 0;
        }
        .m-title {
          font-size: 14px;
          margin-bottom: 16px;
        }
        .address-list {
          max-height: 300px;
          overflow: scroll;
          margin-bottom: 20px;
          &::-webkit-scrollbar {
            display: none; /* 或 width: 0; height: 0; */
          }
          scrollbar-width: none; /* Firefox */
          -ms-overflow-style: none;
        }
        ul {
          height: 50%;
        }
        .address-item {
          padding: 16px;
          border-radius: 2px;
          border: 2px solid #8C8C8C;
          margin-bottom: 8px;
          font-size: 12px;
          &.active {
            border-color: #262626;
          }
          .name {
            span {
              margin-left: 12px;
              font-weight: 600;
            }
          }
          :deep(.van-checkbox) {
            vertical-align: middle;
            margin-right: 10px;
          }
          .info {
            margin-top: 5px;
            p:last-child {
              margin-top: 16px;
            }
          }
          .default-address {
            margin-top: 16px;
            color: #8C8C8C;
          }
        }
        .van-sticky {
          border-top: 1px #ECEBF0 solid;
          background: #FFFFFF;
        }
        .btn-list {
          background: #FFFFFF;
          display: flex;
          column-gap: 12px;
          padding: 12px 16px;
          .s-btn {
            flex: 1;
          }
        }
      }
    }
  }
</style>